﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Yaml.Presentation.Parsing.TokenScanners {
    class MappingKeyTokenScanner : BasicTokenScanner {
        public MappingKeyTokenScanner(Scanner scanner)
            : base(scanner, '?') {
        }

        protected override bool CheckForToken() {
            // Keys are either in flow or must be followed by a space or line break
            return base.CheckForToken() && (!Scanner.State.NotInFlow || Scanner.IsSpaceLineBreakOrNullChar(Reader.PeekRelative(1)));
        }

        protected override void BeforeScan() {
            base.BeforeScan();
            if (Scanner.State.NotInFlow) {
                if (!Scanner.State.SimpleKeys.IsSimpleKeyAllowed) {
                    throw new ScannerException("Mapping keys are not allowed here, " + Start.ToString());
                }
                if (Scanner.State.Indentation.Push(Scanner.State.Column)) {
                    Mark m = Scanner.GetMark();
                    Scanner.Tokens.Push(new Tokens.BlockMappingStartToken(Start, m, Scanner.State.Indentation.Current));
                }
            }
        }

        protected override void AfterScan() {
            base.AfterScan();
            RemoveSimpleKey(Scanner.State.NotInFlow);
        }

        protected override Yaml.Presentation.Tokens.Token CreateToken() {
            return new Tokens.MappingKeyToken(Start, End);
        }
    }
}
